<?php

namespace app\controller\admin\mini;


use app\model\api\Mini;
use app\model\api\MiniAttire;
use app\model\api\MiniCrop;
use app\model\api\MiniImg;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Db;

/**
 * Class Crop
 * @package app\controller\admin\mini
 */
class Crop extends Backend
{
    /**
     * api_log模型对象
     * @var \app\model\api\Log
     */
    protected $model;
    protected $hasSoftDel=0;//是否拥有软删除功能

    protected $noNeedLogin = []; // 无需登录即可请求的方法
    protected $noNeedAuth = ['index', 'info']; // 无需鉴权即可请求的方法
    public $orderRule = ['id' => 'desc'];

    public function _initialize()
    {
        $this->model = new MiniCrop();
    }

    public function index()
    {
        $where   = $this->buildSearchParams();
        $order   = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data = $this->model->where($where)->field(
                'record_id as id,effect,formula,formula_tool,get_way,img,match_good,match_type,unlock'
            )->order($order)->cache(true)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            $data  = $this->model->alias('c')->join('mini_record m','c.record_id=m.id')->field(
                'record_id as id,effect,formula,formula_tool,get_way,img,match_good,match_type,unlock,m.name'
            )->where($where)->order($order)->paginate($limit)->toArray();
        }
        return $this->success('数据获取成功', $data);
    }

    public function miniImg()
    {
        $where   = $this->buildSearchParams();
        $order   = $this->buildOrder();
        $data = (new MiniImg())->order($order)->cache(true)->select()->toArray();
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        Db::startTrans();
        $post=CommonFun::filterPostData($this->request->post());
        $miniImg = (new MiniImg())->column('img','name');
        $record_insData['primary_type']='作物';
        $record_insData['second_type']=!empty($post['second_type'])?$post['second_type']:'';
        $record_insData['name']=!empty($post['name'])?$post['name']:'';
        $record_insData['img_url']=!empty($post['img'])?$post['img']:'';
        $record_insData['if_show']=1;
        $save_record=(new Mini())->insert($record_insData);
        $record_id = (new Mini())->getLastInsID();
        if (!$save_record) throw new \Exception('保存基本信息失败');
        $insData['img'] = !empty($post['img'])?$post['img']:'';
        $insData['record_id']  = $record_id;
        $insData['get_way'] = !empty($post['get_way'])?$post['get_way']:'';
        $insData['effect'] = !empty($post['effect'])?$post['effect']:'';
        $insData['unlock'] = !empty($post['unlock'])?$post['unlock']:'';
        $insData['match_type'] = !empty($post['match_type'])?$post['match_type']:'';
        $formula_name = [];
        $formulaGoods = explode(',',!empty($post['formula'])?$post['formula']:'');
        foreach($formulaGoods as $item){
            if(empty($item)){
                continue;
            }
            $formula_name[] = array(
                'name' => $item,
            );
        }
        $formula=[];
        foreach ($formula_name as $t){
            if (empty($t)){
                continue;
            }
            $formula[]=array(
                'name'=>$t['name'],
                'img'=>!empty($miniImg[$t['name']])?$miniImg[$t['name']]:'',
                'num'=>'1'
            );
        }
        $insData['formula']=json_encode($formula,JSON_UNESCAPED_UNICODE);

        $insData['formula_tool']=json_encode(array(
            'name'=>!empty($post['formula_tool'])?$post['formula_tool']:'',
            'img'=>!empty($miniImg[$post['formula_tool']])?$miniImg[$post['formula_tool']]:''
        ),JSON_UNESCAPED_UNICODE);

        $match_good_name = [];
        $matchGood = explode(',',!empty($post['match_good'])?$post['match_good']:'');
        foreach($matchGood as $item){
            if(empty($item)){
                continue;
            }
            $match_good_name[] = array(
                'name' => $item,
            );
        }
        $match_good=[];
        foreach ($match_good_name as $t){
            if (empty($t)){
                continue;
            }
            $match_good[]=array(
                'name'=>$t['name'],
                'img'=>!empty($miniImg[$t['name']])?$miniImg[$t['name']]:''
            );
        }
        $insData['match_good']=json_encode($match_good,JSON_UNESCAPED_UNICODE);


        try {
            $save = $this->model->save($insData);
            if (!$save) throw new \Exception('保存失败');
            Db::commit();
            $this->clearCache();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }


    public function info(){
        $id = $this->request->param('id');
        $crop = $this->model->where('record_id',$id)->find()->toArray();
        $record_info  = (new Mini())->detail($id);
        $crop['name'] = !empty($record_info['name'])?$record_info['name']:'';
        $crop['second_type'] = !empty($record_info['second_type'])?$record_info['second_type']:'';
        $crop['img']  = !empty($crop['img'])?$crop['img']:'';

        $crop['get_way']  = !empty($crop['get_way'])?$crop['get_way']:'';
        $crop['effect']  = !empty($crop['effect'])?$crop['effect']:'';
        $crop['unlock']  = !empty($crop['unlock'])?$crop['unlock']:'';
        $crop['match_type']  = !empty($crop['match_type'])?$crop['match_type']:'';

        $crop['formula'] = !empty($crop['formula'])?implode(',',array_column(json_decode($crop['formula'],true),'name')):'';
        $crop['formula_tool']=!empty(json_decode($crop['formula_tool'],true)['name'])?json_decode($crop['formula_tool'],true)['name']:'';
        $crop['match_good'] = !empty($crop['match_good'])?implode(',',array_column(json_decode($crop['match_good'],true),'name')):'';
        return $this->success('获取成功', $crop);
    }

    //编辑
    public function edit()
    {
        Db::startTrans();
        $id = $this->request->param('id');
        $post = CommonFun::filterPostData($this->request->post());
        $miniImg = (new MiniImg())->column('img','name');
        $row = $this->model->find($id);
        $record=(new Mini())->find($row['record_id']);
        empty($row) && $this->error('数据不存在');
        empty($record) && $this->error('数据不存在');
        $record->name = !empty($post['name'])?$post['name']:'';
        $record->second_type=!empty($post['second_type'])?$post['second_type']:'';
        $record->img_url=!empty($post['img'])?$post['img']:'';

        $row->img  = !empty($post['img'])?$post['img']:'';
        $row->get_way = !empty($post['get_way'])?$post['get_way']:'';
        $row->effect = !empty($post['effect'])?$post['effect']:'';
        $row->unlock = !empty($post['unlock'])?$post['unlock']:'';
        $row->match_type = !empty($post['match_type'])?$post['match_type']:'';
        $formula_name = [];
        $formulaGoods = explode(',',!empty($post['formula'])?$post['formula']:'');
        foreach($formulaGoods as $item){
            if(empty($item)){
                continue;
            }
            $formula_name[] = array(
                'name' => $item,
            );
        }
        $formula=[];
        foreach ($formula_name as $t){
            if (empty($t)){
                continue;
            }
            $formula[]=array(
                'name'=>$t['name'],
                'img'=>!empty($miniImg[$t['name']])?$miniImg[$t['name']]:'',
                'num'=>'1'
            );
        }
        $row->formula=json_encode($formula,JSON_UNESCAPED_UNICODE);


        $formula_tool = [];
        $formula_tool = array(
                'name' => !empty($post['formula_tool'])?$post['formula_tool']:'',
                'img'=>!empty($post['formula_tool'])?$miniImg[$post['formula_tool']]:''
            );
        $row->formula_tool = json_encode($formula_tool, JSON_UNESCAPED_UNICODE);


        $match_good_name = [];
        $matchGoods = explode(',',!empty($post['match_good'])?$post['match_good']:'');
        foreach($matchGoods as $item){
            if(empty($item)){
                continue;
            }
            $match_good_name[] = array(
                'name' => $item,
            );
        }
        $match_good=[];
        foreach ($match_good_name as $t){
            if (empty($t)){
                continue;
            }
            $match_good[]=array(
                'name'=>$t['name'],
                'img'=>!empty($miniImg[$t['name']])?$miniImg[$t['name']]:'',
            );
        }
        $row->match_good=json_encode($match_good,JSON_UNESCAPED_UNICODE);
        try {
            $save = $row->save();
            $record=$record->save();
            if ($save === false && $record === false) throw new \Exception('保存失败');
            Db::commit();
            $this->clearCache();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    //删除
    public function del()
    {
        Db::startTrans();
        $ids = array_filter($this->request->post('ids'));
        if (!$ids) {
            return $this->error('参数ids不能为空');
        }
        try{
            if ($this->model->where('record_id','in',$ids)->delete() && (new Mini())->where('id','in',$ids)->delete()) {
                Db::commit();
                $this->clearCache();
                return $this->success('数据删除成功');
            } else {
                return $this->error('数据删除失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return $this->exceptionError($e);
        }
    }
}